<template>
  <div
    class="loginPage"
    v-loading="loadinbg"
    element-loading-text="登录验证中..."
  >
    <!-- <div class="copyRight">版权所有：中国电信四川分公司 <span @click="go" style="cursor:pointer">备案号：蜀ICP备05031726号-11</span></div> -->
    <div class="outBox">
      <div class="logoBox">
        <!-- <img src="@/assets/img/login/loginTitle.png" alt /> -->
      </div>
      <div class="rightBox">
        <div class="loginBox" v-if="editPwdShow">
          <el-form
            :model="userForm"
            :rules="userRules"
            ref="userForm"
            class="demo-ruleForm"
          >
            <el-form-item prop="userName">
              <el-input
                v-model.trim="userForm.userName"
                placeholder="请输入账号"
              ></el-input>
            </el-form-item>
            <el-form-item prop="passWord">
              <el-input
                v-model.trim="userForm.passWord"
                placeholder="请输入密码"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <div class="codeContainer">
                <el-input
                  placeholder="请输入验证码"
                  v-model.trim="userForm.code"
                ></el-input>
                <div class="btn">
                  <el-button type="text" @click="getsms">{{
                    show ? "获取验证码" : `${count}S`
                  }}</el-button>
                </div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-checkbox
                v-model="checkoutSecret"
                @change="handleCheck"
              ></el-checkbox>
              <span>已阅读并同意</span
              ><el-button type="text" @click="dialogVisible2 = true"
                >《隐私协议》</el-button
              >及<el-button
                type="text"
                @click="dialogVisible2 = true"
                style="margin: 0"
                >《用户协议》</el-button
              >
            </el-form-item>
            <p style="color: #f56c6c; font-size: 12px; margin-top: -20px">
              {{ msg }}
            </p>
          </el-form>

          <el-button
            :disabled="isAjax"
            type="primary"
            class="loginBtn"
            @click="login('userForm')"
          >
            {{ isAjax ? "登录中..." : "登录" }}
          </el-button>
          <div class="loginOther">
            <el-button type="text" @click="open2">忘记密码？</el-button>
          </div>
        </div>
        <div class="loginBox" v-if="!editPwdShow">
          <div class="tipsBox">
            这是您首次登录本系统，为了您的账号安全请修改登录密码，感谢您的理解与支持~
          </div>
          <div class="formBox">
            <el-form
              :model="editForm"
              :rules="editRules"
              ref="editForm"
              class="demo-ruleForm"
            >
              <el-form-item prop="oldPassword">
                <el-input
                  type="password"
                  v-model.trim="editForm.oldPassword"
                  placeholder="请输入原始密码"
                ></el-input>
              </el-form-item>
              <el-form-item prop="newPassword">
                <el-input
                  type="password"
                  v-model.trim="editForm.newPassword"
                  placeholder="请输入新密码"
                  show-password
                ></el-input>
              </el-form-item>
              <el-form-item prop="confirmPassword">
                <el-input
                  type="password"
                  v-model.trim="editForm.confirmPassword"
                  placeholder="请再次输入新密码"
                  show-password
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <el-button
            :disabled="isAjax"
            class="loginBtn"
            type="primary"
            @click="editPasswordForm('editForm')"
            >确认修改</el-button
          >
        </div>
        <el-dialog
          title="选择公司"
          width="400px"
          :visible.sync="dialogVisible"
          :close-on-click-modal="false"
        >
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" v-no-more-click @click="sureSubmit"
              >确认登录</el-button
            >
          </div>
        </el-dialog>
        <el-dialog
          title=""
          :visible.sync="centerDialogVisible"
          width="20%"
          :modal="false"
        >
          <div slot="title" class="dialog-header-title">
            <i
              class="el-icon-warning-outline"
              style="color: #e6ad1b; font-size: 20px"
            ></i>
            <span>忘记密码?</span>
          </div>
          <span style="margin-left: 20px">
            请联系平台运营管理端管理员重置密码<br />
          </span>
        </el-dialog>
      </div>
    </div>
    <!-- //验证成功的回调函数 //调用的模式 //调用的类型 点选或者滑动 //图片的大小对象-->
    <Verify
      @success="success"
      mode="pop"
      captchaType="blockPuzzle"
      :imgSize="{ width: '330px', height: '155px' }"
      ref="verify"
    ></Verify>
    <el-dialog title="" :visible.sync="dialogVisible" width="900">
      <div>
        <secretAgree />
      </div>
    </el-dialog>
    <el-dialog title="" :visible.sync="dialogVisible2" width="900">
      <div>
        <user-agree></user-agree>
      </div>
    </el-dialog>
  </div>
</template>
 
<script>
import Verify from "@/components/common/verifition/Verify";
import userAgree from "./components/userAgree";
import secretAgree from "./components/secretAgree";
import { mapMutations } from "vuex";
let defaultForm = {
  companyId: "",
  companyName: "",
};
export default {
  name: "",
  components: { Verify, userAgree, secretAgree },
  data() {
    // 验证码校验
    let validCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入六位数字验证码"));
      } else if (/[0-9]$/.test(value) && value.length < 6) {
        callback(new Error("请输入六位数字验证码"));
      } else if (!/[0-9]$/.test(value) || value.length > 6) {
        this.$message.closeAll();
        this.$message.error("仅支持输入6位数字验证码");
      } else {
        callback();
      }
    };
    //手机号码验证
    let validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入11位手机号"));
      } else if (/[0-9]$/.test(value) && value.length < 11) {
        callback(new Error("请输入11位手机号"));
      } else if (!/[0-9]$/.test(value) || value.length > 11) {
        this.$message.closeAll();
        this.$message.error("仅支持输入11位数字");
      } else {
        callback();
      }
    };
    //密码校验
    let validatePass = (rule, value, callback) => {
      if (value === "" || value.length > 32) {
        this.$message.closeAll();
        this.$message.error("账号或密码输入错误");
      } else {
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.editForm.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      loadinbg: false,
      checkoutSecret: false,
      msg: "",
      centerDialogVisible: false,
      dialogVisible: false,
      dialogVisible2: false,
      editPwdShow: true,
      show: true,
      count: 0,
      yzm: "",
      rule: {},
      dialogForm: Object.assign({}, defaultForm),
      dialogVisible: false,
      bgPng: require("@/assets/img/login/loginLeft.png"),
      logo: require("@/assets/img/head/logo.svg"),
      namePng: require("@/assets/img/head/name.svg"),
      // checked: false,

      // userName: "",
      // passWord: "",
      isAjax: false,
      firstMenu: "",
      yzmShow: false,
      validCode: "",
      code: "",
      userForm: {
        userName: "18483285773",
        passWord: "Wyq18483285773?",
        code: "",
      },
      editForm: {
        //修改密码表单
        oldPassword: "", //原始密码
        newPassword: "", //新密码
        confirmPassword: "", //确认密码
      },
      userRules: {
        userName: [{ validator: validPhone, trigger: "blur" }],
        passWord: [{ validator: validatePass, trigger: "blur" }],
        code: [{ validator: validCode, trigger: "blur" }],
      },
      editRules: {
        oldPassword: [
          {
            required: true,
            message: "请输入原密码",
            trigger: "blur",
          },
        ],
        newPassword: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            required: true,
            validator: this.validator.checkPassword,
            trigger: "blur",
          },
        ],
        confirmPassword: [
          {
            required: true,
            message: "",
            validator: validatePass2,
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    if (sessionStorage.getItem("oaLogin")) {
      sessionStorage.removeItem("oaLogin");
      this.loadinbg = true;
      this.getInfo();
      this.getRouter();
    } else {
      this.$cookies.remove("access_token_ygd");
      this.$cookies.remove("authorizationYgd");
      this.$cookies.remove("companyId");
      this.$cookies.remove("companyName");
      this.$cookies.remove("updateHeadImg");
      localStorage.removeItem("companyId");
      localStorage.removeItem("userId");
      sessionStorage.clear();
    }
  },
  methods: {
    handleCheck(val) {
      this.msg = "";
    },
    ...mapMutations(["changeLogin"]),
    open2() {
      this.centerDialogVisible = true;
    },
    //修改密码提交
    editPasswordForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let _data = {
            password: this.editForm.oldPassword,
            newPassword: this.editForm.newPassword,
          };
          // _data.userpwd = this.$md5(this.editForm.oldPassword);
          // _data.newpwd = this.$md5(this.editForm.newPassword);
          // _data.confirmPassword = this.$md5(_data.confirmPassword);
          // _data.confirmPassword = undefined;
          this.$post("/operation/user/aChangePassword", _data).then((res) => {
            if (res.code == 200) {
              this.drawerM = false;
              this.$message({
                message: "密码修改成功",
                type: "success",
              });
              this.$refs[formName].resetFields();
              this.$router.push("/projectList");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getTxyz() {
      this.yzmShow = true;
      this.getCode();
    },
    getyzm() {
      if (!this.show) return;
      const TIME_COUNT = 60;
      if (!this.time) {
        this.count = TIME_COUNT;
        this.show = false;
        this.time = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.time);
            this.time = null;
          }
        }, 1000);
      }
    },
    success(params) {
      // params 返回的二次验证参数, 和登录参数一起回传给登录接口，方便后台进行二次验证
      this.getyzm();
    },
    // 调用短信接口
    async getsms() {
      if (!this.show) return;
      if (!this.userForm.userName) {
        this.$message.error("请输入手机号");
        return false;
      } else {
        let validMobile = /^1[3456789]\d{9}$/;
        if (validMobile.test(this.userForm.userName)) {
        } else {
          this.$message.error("请输入正确的手机号");
          return false;
        }
      }
      if (!this.checkoutSecret) {
        this.msg = "请勾选隐私协议!";
        return false;
      }

      // console.log(this.userForm.userName,'电话');
      this.$store.commit("telephone", this.userForm.userName);
      this.$refs.verify.show();

      // let res = await this.$post("/user/sendSms", { username: this.userName });
      // console.log(res, "短信");
      // if (res.code == 200) {
      //   this.$message({
      //     message: res.msg,
      //     type: "success"
      //   });
      //   this.getyzm();
      // } else {
      //   this.$message.error(res.msg || "验证码发送失败");
      // }
    },
    //获取图形验证码
    async getCode() {
      let id = new Date().getTime();
      localStorage.setItem("uuid", id);
      let res = await this.$post(
        "/user/createImgCodeByCache",
        { webIdentity: id },
        "",
        this.$configs.HTTP_URL,
        { responseType: "blob" }
      );
      this.validCode = window.URL.createObjectURL(
        new Blob([res], { type: "blob" })
      );
    },
    //图形验证
    async goVerification() {
      let uuid = localStorage.getItem("uuid");
      let res = await this.$post("/user/verifyImgCode", {
        vcCacheKey: uuid,
        vcCode: this.code,
      });
      if (res.code == 200) {
        this.yzmShow = false;
      }
    },
    //滑块验证
    onSlideMouseUp(obj) {
      this.login();
    },
    //登录
    login(formName) {
      if (!this.checkoutSecret) {
        this.msg = "请勾选隐私协议!";
        return false;
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.isAjax = true;
          // console.log(this.$md5(this.passWord));
          let res = await this.$post("/operation/auth/telephone/password", {
            telephone: this.userForm.userName,
            password: this.userForm.passWord,
            code: this.userForm.code,
          });
          if (res.code == 200) {
            console.log(res, "登录");

            this.$cookies.set(
              "authorizationYgd",
              res.data["access_token"],
              res.data["expires_in"],
              "/"
            );
            this.$cookies.set(
              "access_token_ygd",
              res.data["access_token"],
              "/"
            );
            this.changeLogin({ authorization: res.data["access_token"] });
            this.getInfo();
            this.getRouter();
            // this.$router.push("/home");
            // await this.getuserInfo();
            // await this.getCompany();
            // this.sureSubmit();
            // this.dialogVisible = true;
          } else {
            this.isAjax = false;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
      // this.$router.push("/projectList");
      // if (!this.yzm) {
      //   this.$message.info("请输入验证码");
      //   return;
      // }
    },
    //获取菜单权限
    async getRouter() {
      let res = await this.$get("/operation/auth/router");
      if (res.code == 200) {
        this.$store.commit("setMenuPermission", res.data);
        // this.firstMenu = res.data[0].children[0].path;
        this.firstMenu = "/homepage";
        console.log("res---获取菜单权限", res);
        this.$store.commit("setActiveMenuIndex", this.firstMenu);

        this.$store.commit("pushBreadListPath", this.firstMenu);
      }
    },

    //用户信息
    async getInfo() {
      let res = await this.$get("/operation/user/getInfo");
      if (res.code == 200) {
        console.log(res);
        this.isAjax = false;
        if (res.data.user.activation == 0) {
          this.editPwdShow = false;
          this.loadinbg = false;
        } else {
          this.$router.push("/projectList");
        }
        this.$store.commit("setYgdUserInfo", res.data);
        localStorage.setItem("userId", res.data.userid);
        sessionStorage.setItem("userOrgyg", res.data.operDepartmentCode);
        sessionStorage.setItem("userOrgNameyg", res.data.operDepartmentName);
        this.$store.commit("userOrgyg", res.data.operDepartmentCode);
        this.$store.commit("userOrgNameyg", res.data.operDepartmentName);
      } else {
        this.isAjax = false;
      }
    },

    async getCompany() {
      let res = await this.$post("orgnazations/getCompanyByUserId");
      if (res.code == 200) {
        this.dialogForm.companyId = res.data.id;
        this.dialogForm.companyName = res.data.name;
      }
    },
    async getuserInfo() {
      let res = await this.$post("user/userWithMenu");
      if (res.code == 200) {
        // this.$store.commit("setMenuPermission", res.data.sysMenus);
        if (res.data.sysMenus.length > 0) {
          this.firstMenu = res.data.sysMenus[0].href;
        } else {
          this.$message.error("该账号未配置菜单");
        }
        this.$store.commit("setYgdUserInfo", res.data);
        localStorage.setItem("userId", res.data.id);
      }
    },
    sureSubmit() {
      // if (this.dialogForm.companyId == "") {
      //   this.$message.error("未获取到登录账号所属公司");
      //   return;
      // }
      // this.$cookies.set("companyId", this.dialogForm.companyId, "/");
      // localStorage.setItem("companyId", this.dialogForm.companyId);
      // this.$cookies.set("companyName", this.dialogForm.companyName, "/");
      let path = sessionStorage.getItem("unAuthPath");
      if (path) {
        this.$router.push(path);
      } else {
        if (this.firstMenu) {
          // this.$router.push(this.firstMenu);
          this.$router.push("/home");
          this.$store.commit("setActiveMenuIndex", this.firstMenu);
          this.$store.commit("clearBreadList");
          this.$store.commit("pushBreadListPath", this.firstMenu);
        }
      }
    },
    go() {
      window.open("https://beian.miit.gov.cn", "_blank");
    },
  },
};
</script>
 
<style scoped lang="scss">
.loginOther {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  // margin-top: 16px;
}

.codeContainer {
  display: flex;

  .btn {
    // border: 1px solid red;
    background-color: #f7f8fb;
    width: 150px;
    height: 42px;
    border: 1px solid #ffffff;
    text-align: center;
  }
}

.loginPage {
  // width: 100vw;
  height: 100vh;
  //background-image: url("@/assets/img/login/bgIcon.png");
  background-size: 100% 100%;
  background-position: center center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  position: relative;

  .copyRight {
    position: absolute;
    bottom: 20px;
    height: 24px;
    line-height: 24px;
    position: absolute;
    bottom: 40px;
    left: 50%;
    margin-left: -100px;
    margin-top: -100px;
    color: #aaa;
  }

  .abc {
    color: #0170fe;
    cursor: pointer;
  }

  .loginBox {
    // box-shadow: 0px 7px 25px 0px rgba(129, 72, 38, 0.16);

    box-shadow: 1px 4px 40px 0px rgba(192, 200, 216, 0.43);
    width: 500px;
    padding: 40px;
    // background: linear-gradient(146deg, rgba(255, 255, 255, 0.7) 0%, #e9ebf3 100%);
    border-radius: 2px;
    background: #ffffff;
    // opacity: 0.7;
    // box-sizing: border-box;
    // padding: 48px;
    // display: flex;
    // flex-direction: column;
    // align-items: center;
    // justify-content: center;

    .titleBox {
      font-size: 20px;
      font-weight: 600;
      margin-bottom: 24px;
    }

    .inputBox {
      width: 100%;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      margin-bottom: 24px;
      background: #f7f8fb !important;

      .iconBox {
        width: 43px;
        height: 40px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        border-left: 1px solid #dcdfe6;
        border-top: 1px solid #dcdfe6;
        border-bottom: 1px solid #dcdfe6;
      }
    }

    .checkBox {
      margin: 10px 0;
      height: 40px;
      width: 300px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
    }

    .formBox {
      width: 100%;

      .formBox {
        margin-bottom: 0px;
      }
    }
  }
}

.rightBox {
  // width: 100%;
  display: flex;
  flex-direction: column;
}

.leftPngBox {
  height: 100%;

  // width: 70%;
  > img {
    height: calc(100% - 189px);
  }
}

.pngBox {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 19px;
}

.outBox {
  width: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding-left: 12%;
}

.tipsBox {
  margin-bottom: 24px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #999999;
  line-height: 22px;
}

.logoBox {
  width: 500px;
  height: 64px;
  margin-bottom: 24px;

  img {
    width: 100%;
    height: 100%;
  }
}

.loginBtn {
  width: 100%;
  height: 48px;
  // background: #0170fe;
  border-radius: 2px;
  margin-top: 40px;
  font-size: 16px;
  color: #ffffff;
}

.forgotPwd {
  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #0170fe;
  line-height: 24px;
  margin-top: 24px;
  cursor: pointer;
}

.yzmClass {
  width: 100px;
  height: 100%;
  text-align: center;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #0170fe;
  // line-height: 24px;
}

.yzmBox {
  width: 100%;
  height: 100%;
  cursor: pointer;
}

::v-deep {
  .loginBox {
    .el-form .demo-ruleForm {
      width: 100%;
    }

    .el-form-item {
      margin-bottom: 24px;
      width: 100%;
    }

    // .inputBox{
    .el-input__inner {
      height: 42px !important;
      color: #333333;
      // font-size: 14px;
      border-radius: 2px;
      border: 1px solid #ffffff;
      background: #f7f8fb !important;
    }

    .el-form-item.is-error .el-input__inner {
      border-color: #f56c6c;
    }

    .el-input {
      background: #f7f8fb !important;
    }

    input:-webkit-autofill {
      background: #f7f8fb !important;
      -webkit-box-shadow: 0 0 0px 1000px #f7f8fb inset !important;

      -webkit-text-fill-color: #333333;
    }

    .el-input-group__append {
      background: #f7f8fb;
      border: 1px solid #ffffff;
    }

    // }
  }

  .verify-box {
    border-radius: 0px !important;
  }

  .veriry-slide {
    border-radius: 0px !important;
  }
}

::v-deep .el-dialog__title {
  font-size: 16px;
  font-weight: 500;
}

::v-deep .el-dialog__body {
  padding-top: 10px !important;
}
</style>